#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

#include "uvbotlib.h"

int roll(int sides)
{
    return rand() % sides + 1;
}

// getFacingSq FIND TERRAIN IN DIRECTION BOT IS FACING
// INDEXES INTO MAP STRING GO INTO SQUARE LIKE THIS:
//  0 1 2 
//  3 4 5
//  6 7 8
// WHERE 4 IS THE SQUARE THE BOT IS OCCUPYING

char getFacingSq(BotStatus& status)
{
    int indexes[] = {1, 2, 5, 8, 7, 6, 3, 0};
    int face;
    char terrain;

    face = (status.getFacing() + 23) / 45;
    if (face > 7) {  // VALID VALUES ARE 0 THROUGH 7
	face = 0;
    }
    terrain =  status.getMap()[indexes[face]];
    /***********
    cout << "getFacingSq facing: " << status.getFacing() 
	 << " face: " << face
	 << " index: " << indexes[face] 
	 << " terrain: " << terrain 
	 << endl;
    *********/
    return terrain;
}

string makeCmd(BotStatus& status)
{
    int die;
    string cmd;
    char terrain;

    terrain = getFacingSq(status);

    die = roll(8);
    switch(die) {
    case 1:
    case 2:
	cmd = "move 0";
	break;
    case 3:
	cmd = "move 45";
	break;
    case 4:
	cmd = "move -45";
	break;
    case 5:
	cmd = "fire 0";
	break;
    case 6:
	cmd = "scan";
	break;
    case 7:
	cmd = "turn 90";
	break;
    case 8:
	cmd = "turn -90";
	break;
    default:
	cmd = "move 0";
	break;
    }
    return cmd;
}

int main(int argc, char** argv)
{
    UvBot bot;
    BotStatus status;
    string cmd, result;
    ConnectionWin conn;
    string hostName, name;
    int port;
    bool destroyed = false;
    
    srand(time(NULL));

    hostName = "localhost";
    port = 4688;

    if (argc > 1) {
        name = argv[1];
    }

    if (argc > 2) {
	port = atoi(argv[2]);
    }

    if (argc > 3) {
	hostName = argv[3];
    }

    bot.connect(hostName, port, name);

    while (!destroyed) {
	cmd = makeCmd(status);
        // cout << "CMD: " << cmd << endl;
	result = bot.doCmd(cmd);
	// cout << result << endl;
	status.parse(result);
	// cout << "Done parsing result" << endl;
    }
    
    // cout << "Destroyed" << endl;
	return 0;
}

